<template>
	<div style="width: 100%; height: 100%; position: relative;">
		<view class="container">
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>选择商品类型</span>
				</div>
				<div>
					<div class="ny-card-itam">
						<image src="../../../static/image/ecard-types.png" mode=""></image>
						<image src="../../../static/image/active-types.png" mode=""></image>
					</div>
				</div>
			</el-card>
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>卡密设置</span>
				</div>
				<div>
					<el-form ref="form" :model="form" label-width="90px">
						<el-form-item label="网盘名称:">
							<el-select v-model="form.netdisk.netdisk_name" placeholder="请选择网盘名称">
								<el-option label="百度网盘" value="百度网盘"></el-option>
								<el-option label="阿里云网盘" value="阿里云网盘"></el-option>
								<el-option label="夸克网盘" value="夸克网盘"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="网盘地址:" prop="netdisk.netdisk_url" :rules="[
						      { required: true, message: '网盘地址不能为空'}]">
							<el-input style="width: 500px;" maxlength="100" show-word-limit
								v-model="form.netdisk.netdisk_url"></el-input>
						</el-form-item>
						<el-form-item label="提取码:" prop="netdisk.password" :rules="[
						      { required: true, message: '提取码不能为空'}]">
							<el-input style="width: 500px;" maxlength="100" show-word-limit
								v-model="form.netdisk.password"></el-input>
						</el-form-item>
						<el-form-item label="解压码:">
							<el-input style="width: 500px;" maxlength="100" show-word-limit
								v-model="form.netdisk.decode"></el-input>
						</el-form-item>

					</el-form>
				</div>
			</el-card>
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>选择图包分类</span>
				</div>
				<div>
					<el-select v-model="form.picture_type" multiple placeholder="请选择">
						<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</div>
			</el-card>
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>图包信息设置</span>
				</div>
				<div>
					<el-form ref="form" :model="form" label-width="90px">
						<el-form-item label="图包名称:" prop="name" :rules="[
						      { required: true, message: '图包名称不能为空'}]">
							<el-input style="width: 500px;" maxlength="100" show-word-limit
								v-model="form.name"></el-input>
						</el-form-item>
						<el-form-item label="副标题:" prop="title" :rules="[
						      { required: true, message: '副标题不能为空'}]">
							<el-input style="width: 500px;" maxlength="100" show-word-limit v-model="form.title"
								autocomplete="off"></el-input>
						</el-form-item>
						<el-form-item label="售价:" prop="price" :rules="[
						      { required: true, message: '售价不能为空'}
						    ]">
							<el-input style="width: 500px;" v-model="form.price" maxlength="3"
								autocomplete="off"></el-input>
						</el-form-item>
						<el-form-item label="上架状态:" prop="delivery">
							<el-switch v-model="form.state"></el-switch>
						</el-form-item>
					</el-form>
				</div>
			</el-card>
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>图包轮播图(商品预览图)(建议尺寸1:1,最多四张) 注:默认第一张为封面</span>
				</div>
				<div>
					<ul class="ny-upload-ul">
						<li v-for="itam in form.picture_swiper">
							<div>
								<img :src="itam" alt="" />
								<span class="ny-upload-span">
									<span @click="handlePictureCardPreview(itam)" class="ny-upload-span-itam1"><i
											class="el-icon-zoom-in"></i></span>
									<span @click="deleteFiles(itam)" class="ny-upload-span-itam2"><i
											class="el-icon-delete"></i></span>
								</span>
							</div>
						</li>
					</ul>
					<div class="ny-upload-img" @click="uploaD">
						<i data-v-293d3606 class="el-icon-plus"></i>
					</div>
					<el-dialog :visible.sync="dialogVisible">
						<img width="100%" :src="dialogImageUrl" alt="">
					</el-dialog>
				</div>
			</el-card>
			<el-card class="box-card" shadow="never">
				<div slot="header" class="clearfix">
					<span>图包详情介绍</span>
				</div>
				<div>
					<div style="border: 1px solid #ccc; width: 900px;">
						<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
							:mode="mode" />
						<Editor style="height: 500px; overflow-y: hidden;" v-model="html" :defaultConfig="editorConfig"
							:mode="mode" @onCreated="onCreated" />
					</div>
				</div>
			</el-card>


		</view>
		<!-- 提交 -->
		<div class="ny-from-primary">
			<div class="ny-from-primary-box">
				<el-button @click="onSubmits" type="primary">提交</el-button>
				<el-button>取消</el-button>
			</div>
		</div>

	</div>
</template>

<script>
	import {
		Editor,
		Toolbar
	} from '@wangeditor/editor-for-vue'
	import {
		DomEditor
	} from '@wangeditor/editor'


	export default {
		components: {
			Editor,
			Toolbar
		},
		data() {
			return {
				form: {
					name: '', //图包名称
					title: '', //副标题
					price: '', //售价
					state: true, //上架状态
					picture_swiper: [], //图包详情图
					content: '', //图包详情介绍
					netdisk: {
						netdisk_name: '',
						netdisk_url: '',
						password: '',
						decode: '无', //解压码
					}, //网盘信息
					goods_type: '电子卡密', //商品类型
					picture_type: [],
					examine: '待审核', //审核状态
					create_date: '', //创建时间
					sort: 100, //排序
					author_id: '6625e7c9fe975f74409546d6', //作者id
					author_name: '柠玉',
					volume: 0, //销量
				},

				options: [],
				value: '',
				list_num: [],
				dialogVisible: false,
				dialogImageUrl: '',
				toolbarConfig: {
					toolbarKeys: [
						"bold", "underline", "italic", "through", "code", "sub", "sup", "clearStyle", "color",
						"bgColor", "fontSize", "fontFamily", "indent", "delIndent",
						"justifyLeft", "justifyRight", "justifyCenter", "justifyJustify",
						"lineHeight", "emotion", "headerSelect", "bulletedList", "numberedList"
					]

				}, //编辑器工具栏设计
				editorConfig: {
					placeholder: '请输入内容...'
				},
				html: '<p>hello</p>',
				editor: null,
				mode: 'default',
			}
		},
		async beforeCreate() {
			// 获取图包类型所有数据
			let col = uniCloud.importObject('indexObj', {
				customUI: true
			})
			let list = await col.getImagepackTag()
			list.data.data.map((n, m) => {
				this.options.push({
					value: n._id,
					label: n.name
				})
			})
			console.log(list.data.data)
		},
		created() {
			let time = this.gettime()
			this.form.create_date = time
		},
		beforeDestroy() {
			const editor = this.editor
			if (editor == null) return
			editor.destroy() // 组件销毁时，及时销毁编辑器
		},
		methods: {
			onCreated(editor) {
				this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file;
				this.dialogVisible = true;
			},
			uploaD(item) {
				let that = this
				if (this.list_num.length <= 4) {
					uni.chooseImage({
						count: 4,
						sizeType: ['compressed'],
						crop: {
							width: "500px"
						},
						success(res) {
							console.log(res.tempFilePaths);
							for (let i = 0; i < res.tempFilePaths.length; i++) {
								uni.showLoading({
									title: '上传中...'
								})
								let filePath = res.tempFilePaths[i] // 选择图片的临时路径
								let name = res.tempFiles[i].name // 选择图片的名称.后缀名
								let aaa = name.replace('.jpg', '').replace('.JPG', '').replace('.png', '')
								let asd = aaa.split('-')[2] - 0
								// 生成随机名字
								let result = '';
								const characters =
									'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
								for (let i = 0; i < 8; i++) {
									result += characters.charAt(Math.floor(Math.random() * characters.length));
								}
								var handleImage = function(imgSrc) {
									// 创建一个Image对象
									var img = new Image();
									img.src = imgSrc;
									// 定义图片加载完成时的处理函数
									var onLoadHandler = function() {
										// 移除事件监听器，确保只执行一次
										img.removeEventListener('load', onLoadHandler);
										// 创建一个Canvas元素
										var canvas = document.createElement('canvas');
										var ctx = canvas.getContext('2d');
										// 设置Canvas的尺寸
										var maxWidth = 800; // 设置最大宽度
										var maxHeight = 1500; // 设置最大高度
										var imgWidth = img.width;
										var imgHeight = img.height;
										if (imgWidth > maxWidth || imgHeight > maxHeight) {
											var ratio = Math.min(maxWidth / imgWidth, maxHeight /
												imgHeight);
											imgWidth *= ratio;
											imgHeight *= ratio;
										}
										canvas.width = imgWidth;
										canvas.height = imgHeight;
										// 在Canvas上绘制图片
										ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
										// 将Canvas中的图片转换为DataURL
										var compressedDataURL = canvas.toDataURL('image/jpeg',
											0.8); // 压缩质量为0.8
										// 输出压缩后的DataURL
										console.log('压缩后的图片DataURL：', compressedDataURL);

										// 调用上传的接口
										that.uploadFileImg(compressedDataURL, result)
									}
									// 监听图片加载完成事件
									img.addEventListener('load', onLoadHandler);
								}
								handleImage(filePath);
							}
						}

					});
				}
			},
			uploadFileImg(filePath, result) {
				let that = this
				uniCloud.uploadFile({
					filePath: filePath, //要上传的文件对象
					cloudPath: `ningyuApp/image/uploader/${result}.png`,
					cloudPathAsRealPath: true,
					success(res) {
						let imageUrl = res.fileID //云端返回的图片地址
						uniCloud.callFunction({ //调用云端函数，把图片地址写入表
							name: 'addImage', //云函数名称
							data: { //提交给云端的数据
								imageUrl: imageUrl,
								createTime: result,
							},
							success: (res) => {
								//console.log('数据插入成功')
								console.log(res)

								that.form.picture_swiper.push(
									`https://mp-ab4407e3-0701-45ce-b458-b02edc2d6474.cdn.bspapp.com/ningyuApp/image/uploader/${result}.png`
								)
								uni.showToast({
									title: '壁纸添加成功！！',
									duration: 1000
								});
								this.$emit('fuc','goodList')
							},
							fail: (err) => {
								console.log(err)
								uni.showToast({
									title: '添加失败，类型已存在',
									duration: 1000
								});
							},
							complete: () => {

							}
						})
					},
					fail(err) {
						console.log(err)
					},
					complete() {
						uni.hideLoading()
					}
				});
			},
			deleteFiles(res) {
				this.form.picture_swiper = this.form.picture_swiper.filter(m => m != res)
			},
			//提交表单
			async onSubmits() {
				this.form.content = this.editor.getHtml()
				let form = this.form
				let col = uniCloud.importObject('indexObj', {
					customUI: true
				})

				if (form.name != '' && form.title != '' && form.price != '' && form.netdisk.netdisk_name != '' &&
					form.netdisk.netdisk_url != '' &&
					form.netdisk.password != '' &&
					form.picture_swiper != '' &&
					form.picture_type != '') {
					const priceRegex = /^\d+(\.\d{1,2})?$/;
					this.form.price = this.form.price - 0
					if (priceRegex.test(this.form.price)) {
						let res = await col.addgoodsPicture(this.form)
						this.$message({
							message: '创建商品成功!!!',
							type: 'success'
						});
						this.$emit('fuc', 'goodList', '');
					} else {
						this.$message({
							message: '价格格式有误！！',
							type: 'warning'
						});
					}

				} else {
					this.$message({
						message: '请填写完整信息',
						type: 'warning'
					});
				}

			},
			// 获取时间
			gettime() {
				var date = new Date()
				var year = date.getFullYear()
				var month = date.getMonth() + 1
				var day = date.getDate()
				var hour = date.getHours()
				var fen = date.getMinutes()

				if (month <= 9) {
					month = `0${month}`
				}
				if (day <= 9) {
					day = `0${day}`
				}
				if (hour <= 9) {
					hour = `0${hour}`
				}
				if (fen <= 9) {
					fen = `0${fen}`
				}
				return `${year}${month}${day}${hour}${fen}`
			},

		},

	}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss">
	.container {
		margin: 0;
		padding: 0;
		background-color: #fff;
		width: 100%;
		height: 90%;
		overflow-y: auto;
		overflow-x: hidden;

		.box-card {
			width: 95%;
			margin: 0 auto;
			margin-top: 10px;
			margin-bottom: 20px;

			.ny-card-itam {
				position: relative;
				width: 208px;
				height: 74px;

				image {
					position: absolute;
					width: 100%;
					height: 100%;
				}
			}

			.ny-upload-ul {
				margin: 0;
				display: inline;
				vertical-align: top;

				li {
					overflow: hidden;
					background-color: #fff;
					border: 1px solid #c0ccda;
					border-radius: 6px;
					box-sizing: border-box;
					width: 148px;
					height: 148px;
					margin: 0 8px 8px 0;
					display: inline-block;

					div {
						width: 100%;
						height: 100%;
						display: block;
						unicode-bidi: isolate;
						position: relative;

						img {
							width: 100%;
						}

						.ny-upload-span:hover {
							opacity: 1;
						}

						.ny-upload-span {
							position: absolute;
							width: 100%;
							height: 100%;
							left: 0;
							top: 0;
							cursor: default;
							text-align: center;
							color: #fff;
							opacity: 0;
							font-size: 20px;
							background-color: rgba(0, 0, 0, .5);
							transition: opacity .3s;
							line-height: 148px;

							.ny-upload-span-itam1 {
								cursor: pointer;
								padding: 0 10px;
							}

							.ny-upload-span-itam2 {
								padding: 0 10px;
								cursor: pointer;
							}
						}
					}

				}
			}

			.ny-upload-img {
				display: inline-block;
				background-color: #fbfdff;
				border: 1px dashed #c0ccda;
				border-radius: 6px;
				-webkit-box-sizing: border-box;
				box-sizing: border-box;
				width: 148px;
				height: 148px;
				cursor: pointer;
				line-height: 146px;
				vertical-align: top;
				position: relative;
				text-align: center;
				color: #8c939d;
				font-size: 26px;
			}

			.ny-upload-img:hover {
				border-color: #409EFF;
				color: #409EFF;
			}
		}

	}

	.ny-from-primary {
		width: 99%;
		height: 70px;
		background-color: #fff;
		position: absolute;
		bottom: 0px;
		border-radius: 10px 10px 0 0;

		.ny-from-primary-box {
			margin: 0 auto;
			width: 160px;
			height: 40px;
			margin-top: 15px;
		}
	}
</style>